package com.fsp.blog.service.iml;

import com.alibaba.fastjson.JSON;
import com.fsp.blog.dao.SysUserMapper;
import com.fsp.blog.pojo.SysUser;
import com.fsp.blog.service.LoginService;
import com.fsp.blog.service.SysUserService;
import com.fsp.blog.utils.JWTUtils;
import com.fsp.blog.vo.ErrorCode;
import com.fsp.blog.vo.Result;
import com.fsp.blog.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fushengping
 * @className LoginServiceImpl
 * @description
 * @date 2021/11/10 0:17
 */
@Service
@Transactional
public class LoginServiceImpl implements LoginService {
    private static final String slat = "mszlu!@#"; //加密盐
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SysUserService sysUserService;
    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1.检查参数是否合法
         * 2.根据输入的用户名和密码去user表中进行查询是否存在
         * 3.如果不存在，登录失败
         * 4.如果存在，使用jwt，生成token，返回给前端
         * 5.token放入redis中-->  redis  token:user信息，设置过期时间
         * (登录认证的时候，先去认证token是否合法，再去认证redis中是否存在)
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        //1.参数是否合法
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        password = DigestUtils.md5Hex(password + slat);
        //2.判断用户是否存在
        SysUser sysUser = sysUserService.findUser(account,password);
        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        //3.生成token
        String token = JWTUtils.createToken(sysUser.getId());
        //4.存入redis中(设置过期时间一天)
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Map<String, Object> checkToken = JWTUtils.checkToken(token);
        if (checkToken == null) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);//解析对象
        return sysUser;
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }

    @Override
    public Result register(LoginParam loginParam) {
        /**
         * 1.验证传入的参数格式是否正确
         * 2.根据用户名参数查询是否存在该用户，有则返回已存在
         * 3.若传入参数的用户查询不存在，则插入用户表中
         * 4.将该参数进行jwt加密，存入redis中
         * 5.加上事务注解,确保中途错误不会插入数据
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickName = loginParam.getNickname();
        if (StringUtils.isBlank(account)
            || StringUtils.isBlank(password)
            || StringUtils.isBlank(nickName)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = sysUserService.findUserByAccount(account);
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        /*将传入的参数存入sysUser中*/
        sysUser = new SysUser();
        sysUser.setAccount(account);
        //密码需进行md5加密
        sysUser.setPassword(DigestUtils.md5Hex(password+slat));
        sysUser.setNickname(nickName);
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        //插入表中
        sysUserService.save(sysUser);
        //进行token加密，存入redis中
        String token = JWTUtils.createToken(sysUser.getId());

        redisTemplate.opsForValue().set("TOKEN_"+token,JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
